package com.saicmotor.floatingwindow;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;

/**
 * @Author xinxinzhang
 * @Date 2022/08/18
 **/
public class FloatingWindow extends Service {

    private ViewGroup floatView;
    private WindowManager.LayoutParams floatWindowLayoutParams;
    private int LAYOUT_TYPE;
    private WindowManager windowManager;
    private EditText editText;
    private Button btn_max;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;

        // 可以使用WindowManager对Window(View)进行添加、更新和删除操作
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        // LayoutInflater作用类似于 findViewById()，找layout下xml布局文件并实例化
        LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
        floatView = (ViewGroup) inflater.inflate(R.layout.floating_layout, null);

        btn_max = floatView.findViewById(R.id.btn_max);
        editText = floatView.findViewById(R.id.edt_des);

        editText.setText(Common.currDes);
        editText.setSelection(editText.getText().toString().length());
        editText.setCursorVisible(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_TYPE = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_TYPE = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }

        floatWindowLayoutParams = new WindowManager.LayoutParams(
                (int) (width * 0.55f),
                (int) (height * 0.55f),
                LAYOUT_TYPE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        floatWindowLayoutParams.gravity = Gravity.CENTER;
        floatWindowLayoutParams.x = 0;
        floatWindowLayoutParams.y = 0;

        windowManager.addView(floatView, floatWindowLayoutParams);

        btn_max.setOnClickListener((v) -> {
            stopSelf();

            windowManager.removeView(floatView);
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(intent);
        });


        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Common.currDes = editText.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        floatView.setOnTouchListener(new View.OnTouchListener() {

            WindowManager.LayoutParams updatedFloatWindowLayoutParams = floatWindowLayoutParams;
            double x = 0.0;
            double y = 0.0;
            double px = 0.0;
            double py = 0.0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        x = updatedFloatWindowLayoutParams.x;
                        y = updatedFloatWindowLayoutParams.y;
                        px = motionEvent.getRawX();
                        py = motionEvent.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        updatedFloatWindowLayoutParams.x = (int) (x + motionEvent.getRawX() - px);
                        updatedFloatWindowLayoutParams.y = (int) (y + motionEvent.getRawY() - py);

                        windowManager.updateViewLayout(floatView, updatedFloatWindowLayoutParams);

                }
                return true;
            }
        });

        editText.setOnTouchListener((view, motionEvent) -> {
            editText.setCursorVisible(true);
            WindowManager.LayoutParams updatedFloatParams = floatWindowLayoutParams;
            updatedFloatParams.flags =
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
            windowManager.updateViewLayout(floatView, updatedFloatParams);
            return false;
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
        windowManager.removeView(floatView);
    }
}
